package com.wsjzzcbq.wsjzcode.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.wsjzzcbq.wsjzcode.bean.ExecuteResult;
import com.wsjzzcbq.wsjzcode.bean.R;
import com.wsjzzcbq.wsjzcode.bean.SqlCode;
import com.wsjzzcbq.wsjzcode.code.CodeRunResultMap;
import com.wsjzzcbq.wsjzcode.consts.LangTypeEnum;
import com.wsjzzcbq.wsjzcode.consts.MsgConsts;
import com.wsjzzcbq.wsjzcode.param.CodeParam;
import com.wsjzzcbq.wsjzcode.queue.CodeExecuteQueue;
import com.wsjzzcbq.wsjzcode.service.SqlService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import java.util.UUID;

/**
 * SqlServiceImpl
 *
 * @author wsjz
 * @date 2023/07/07
 */
@Service
public class SqlServiceImpl implements SqlService {

    @Override
    public R<?> execute(CodeParam param) {
        if (StringUtils.isBlank(param.getCode())) {
            return R.custom(2, MsgConsts.SQL_NOT_EMPTY);
        }
        SqlCode code = new SqlCode();
        String number = UUID.randomUUID().toString();
        code.setNumber(number);
        code.setType(LangTypeEnum.Sql);
        code.setCode(param.getCode());

        try {
            CodeExecuteQueue.queue.put(code);
            CodeRunResultMap.map.put(number, new ExecuteResult());
        } catch (InterruptedException e) {
            return R.custom(2, e.getMessage());
        }

        JSONObject json = queuingInstruction(number);

        return R.success(json);
    }
}
